<template>
  <div v-show="$route.name == 'process-list'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>肉码生产成本</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <div style="margin-bottom: 20px;">肉码生产成本记录</div>
      <!-- 搜索与添加区域 -->
      <el-row class="query" v-if="groupid === 0">
        <el-col :span="24">
          <el-date-picker
            v-model="exportTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <el-button type="warning" @click="exportExcel" style="margin-left: 10px;">导出至excel</el-button>
        </el-col>
      </el-row>
      <el-table
        border
        v-loading="loading"
        :data="processData"
        style="margin-top: 10px;">
        <el-table-column label="日期" prop="process_time" min-width="110" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.row.process_time ? new Date(scope.row.process_time).toLocaleDateString().split('/').join('-'): '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原料总成本/半成品生产成本" prop="material_total" min-width="110" align="center" v-if="groupid === 0">
          <template slot-scope="scope">
            <span>{{ parseFloat(scope.row.material_total).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参考总成本" prop="default_total" min-width="110" align="center" v-if="groupid === 0">
          <template slot-scope="scope">
            <span>{{ parseFloat(scope.row.default_total).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="clickButton(scope.row.process_time, 1)" v-if="scope.row.act">编辑</el-button>
            <el-button size="mini" type="primary" @click="clickButton(scope.row.process_time, 2, scope.row.act)" v-if="scope.row.id">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pager.currPage"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.totalCount">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      groupid: '',
      loading: false,
      pager: {
        currPage: 1,
        pageSize: 10,
        totalCount: 0
      },
      processData: [],
      exportTime: ''
    }
  },
  mounted() {
    this.getUserInfo()
    this.getProcessList()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const { data: result } = await this.$http.get('/user/' + localStorage.userid)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.groupid = result.data.groupid === '' ? '' : result.data.groupid * 1
    },
    async getProcessList() {
      this.loading = true
      const params = {
        page: this.pager.currPage,
        pageSize: this.pager.pageSize
      }
      const { data: result } = await this.$http.get('/process', { params: params })
      if (result.status !== 200) {
        this.loading = false
        return this.$message.error(result.msg)
      }
      this.loading = false
      this.processData = result.data
      this.pager = result.pager
    },
    handleSizeChange(pageSize) {
      this.pager.pageSize = pageSize
      this.getProcessList()
    },
    handleCurrentChange(currentPage) {
      this.pager.currPage = currentPage
      this.getProcessList()
    },
    clickButton(process_time, type, flag = 0) {
      if (type === 1 ) {
        this.$router.push({
          name: 'process-update',
          params: { process_time: process_time }
        })
      } else if (type === 2) {
        this.$router.push({
          name: 'process-detail',
          params: { process_time: process_time, flag: flag }
        })
      }
    },
    // 导出
    async exportExcel() {
      this.loading = true
      var data = {}
      if (this.exportTime) {
        const startTime = new Date(this.exportTime[0])
        const syear = startTime.getFullYear() // 获取当前年份
        const smonth = startTime.getMonth() + 1 // 获取当前月份(0-11,0代表1月所以要加1);
        const sday = startTime.getDate() // 获取当前日（1-31）
        const endTime = new Date(this.exportTime[1])
        const eyear = endTime.getFullYear() // 获取当前年份
        const emonth = endTime.getMonth() + 1 // 获取当前月份(0-11,0代表1月所以要加1);
        const eday = endTime.getDate() // 获取当前日（1-31）
        if (startTime) {
          data.startTime = `${syear}-${smonth}-${sday}`
        }
        if (endTime) {
          data.endTime = `${eyear}-${emonth}-${eday}`
        }
      }
      await this.$http.post('/process/export', data, { type: 'json',responseType:'blob' }).then(res => {
        if (res.status === 200) {
          const blob = res.data
          const reader = new FileReader()
          reader.readAsDataURL(blob)
          reader.onload = (e) => {
            const a = document.createElement('a')
            a.download = '生产成本导出.xlsx'
            a.href = e.target.result
            a.click()
          }
          this.loading = false
          return this.$message.success('导出成功')
        }
        this.loading = false
        return this.$message.error(res.msg)
      }).catch (() => {
        this.loading = false
        return this.$message.error('导出失败')
      })
    }
  }
}
</script>
